<template>
	<view class="practice-container">
		<!-- 顶部状态栏 -->
		<view class="status-bar">
			<text class="time">{{ formatTime(currentTime) }}</text>
			<text class="progress">{{ currentQuestion }}/{{ totalQuestions }}</text>
			<text class="practice-type">{{ practiceType }}</text>
		</view>

		<!-- 主内容区 -->
		<view class="content-area">
			<view class="question-section">
				<view class="question-container">
					<text class="question">{{ currentQuestionData.expression }} =</text>
					<view class="answer-display">
						<text class="answer">{{ userAnswer || '?' }}</text>
					</view>
				</view>

				<view class="standards">
					<text>{{ timeStandards }}</text>
				</view>
			</view>

			<!-- 操作按钮 -->
			<view class="action-buttons">
				<view class="btn restart" @click="restartPractice">
					<uni-icons type="refresh" size="24" color="#fff"></uni-icons>
					<text>重开</text>
				</view>
				<view class="btn clear" @click="clearAnswer">
					<text>清空</text>
				</view>
				<view class="btn backspace" @click="backspace">
					<text>退格</text>
				</view>
			</view>
		</view>

		<!-- 数字键盘 -->
		<view class="number-pad">
			<view v-for="(num, index) in numberPad" :key="index" class="num-btn" @click="inputNumber(num)">
				<text>{{ num }}</text>
			</view>
			<view class="num-btn confirm" @click="checkAnswer">
				<text>确定</text>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,
		onUnmounted,
		computed
	} from 'vue';

	const props = defineProps({
		questionCount: {
			type: Number,
			default: 10
		},
		practiceType: {
			type: String,
			required: true
		}
	});

	// 计时器相关
	const currentTime = ref(0);
	let timer = null;

	// 题目相关
	const totalQuestions = ref(props.questionCount);
	const currentQuestion = ref(1);
	const userAnswer = ref('');
	const questions = ref([]);
	const currentQuestionData = ref({});
	const correctCount = ref(0);

	// 数字键盘布局
	const numberPad = ref(['1', '2', '3', '4', '5', '6', '7', '8', '9', '.', '0']);

	// 根据题型和题目数量设置动态时间标准
	const timeStandards = computed(() => {
		// 基础题目数量（10题）的时间标准
		const baseStandards = {
			// 加减法类
			'两位数加减': {
				qualified: 60,
				good: 45,
				excellent: 30
			},
			'凑整百练习': {
				qualified: 50,
				good: 35,
				excellent: 20
			},
			'三位数加法': {
				qualified: 90,
				good: 70,
				excellent: 50
			},
			'三位数减法': {
				qualified: 90,
				good: 70,
				excellent: 50
			},
			'三位数加减': {
				qualified: 100,
				good: 80,
				excellent: 60
			},
			'多数相加': {
				qualified: 120,
				good: 90,
				excellent: 60
			},

			// 乘法类
			'两位数乘一位数': {
				qualified: 90,
				good: 70,
				excellent: 50
			},
			'三位数乘一位数': {
				qualified: 120,
				good: 90,
				excellent: 60
			},
			'两位数乘11': {
				qualified: 40,
				good: 30,
				excellent: 20
			},
			'两位数乘15': {
				qualified: 50,
				good: 35,
				excellent: 25
			},
			'两位数乘两位数': {
				qualified: 150,
				good: 120,
				excellent: 90
			},
			'常见平方数': {
				qualified: 30,
				good: 20,
				excellent: 10
			},

			// 除法类
			'三位数除以一位数': {
				qualified: 120,
				good: 90,
				excellent: 60
			},
			'三位数除以两位数': {
				qualified: 150,
				good: 120,
				excellent: 90
			},
			'五位数除以三位数': {
				qualified: 180,
				good: 150,
				excellent: 120
			},

			// 特殊题型
			'乘法估算': {
				qualified: 60,
				good: 45,
				excellent: 30
			},

			// 默认
			'default': {
				qualified: 90,
				good: 60,
				excellent: 30
			}
		};

		// 获取当前题型的基础标准
		const base = baseStandards[props.practiceType] || baseStandards.default;

		// 计算题目数量调整系数 (以10题为基准)
		const countFactor = props.questionCount / 10;

		// 使用对数调整，避免时间增长过快
		const adjustTime = (time) => {
			return Math.round(time * (0.8 + 0.2 * Math.log2(countFactor + 1)));
		};

		// 返回格式化后的字符串
		return `合格: ${adjustTime(base.qualified)}s 良好: ${adjustTime(base.good)}s 优秀: ${adjustTime(base.excellent)}s`;
	});

	// 格式化时间显示
	const formatTime = (seconds) => {
		const mins = Math.floor(seconds / 60);
		const secs = seconds % 60;
		return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
	};

	// 根据题型生成题目
	const generateQuestions = () => {
		const newQuestions = [];
		const history = new Set(); // 每个题目独立检查
		for (let i = 0; i < totalQuestions.value; i++) {
			let question;
			switch (props.practiceType) {
				case '两位数加减':
					question = generateTwoDigitAddSub(history);
					break;
				case '凑整百练习':
					question = generateRoundHundred(history);
					break;
				case '三位数加法':
					question = generateThreeDigitAdd(history);
					break;
				case '三位数减法':
					question = generateThreeDigitSub(history);
					break;
				case '三位数加减':
					question =  generateThreeDigitAddSub(history);
					break;
				case '多数相加':
					question =  generateMultiAdd(history);
					break;
				case '两位数乘一位数':
					question =  generateTwoDigitMulOneDigit(history);
					break;
				case '三位数乘一位数':
					question =  generateThreeDigitMulOneDigit(history);
					break;
				case '两位数乘11':
					question =  generateTwoDigitMul11(history);
					break;
				case '两位数乘15':
					question =  generateTwoDigitMul15(history);
					break;
				case '两位数乘两位数':
					question =  generateTwoDigitMulTwoDigit(history);
					break;
				case '常见平方数':
					question =  generateCommonSquares(history);
					break;
				case '三位数除以一位数':
					question =  generateThreeDigitDivOneDigit(history);
					break;
				case '三位数除以两位数':
					question =  generateThreeDigitDivTwoDigit(history);
					break;
				case '乘法估算':
					question =  generateEstimation(history);
					break;
				case '五位数除以三位数':
					question =  generateFiveDigitDivThreeDigit(history);
					break;
				default:
					return generateTwoDigitAddSub(history);
			}

			newQuestions.push(question);
		}

		questions.value = newQuestions;
		currentQuestionData.value = newQuestions[0];
	};

	// 公用验证方法
	function validateQuestion(question, history) {
		if (!question || question.answer === undefined) return false;
		const hash = `${question.expression}=${question.answer}`;
		return !history.has(hash);
	}

	// 1. 两位数加减
	function generateTwoDigitAddSub(history) {
		let attempts = 0;
		while (attempts++ < 20) {
			const num1 = Math.floor(Math.random() * 90) + 10;
			const num2 = Math.floor(Math.random() * 90) + 10;
			const isAdd = Math.random() > 0.5;
			const answer = isAdd ? num1 + num2 : num1 - num2;

			if (!isAdd && answer < 0) continue;

			const question = {
				expression: `${num1} ${isAdd ? '+' : '-'} ${num2}`,
				answer: answer
			};

			if (validateQuestion(question, history)) {
				history.add(`${question.expression}=${question.answer}`);
				return question;
			}
		}
		return {
			expression: "23 + 57",
			answer: 80
		}; // 默认题目
	}

	// 2. 凑整百练习
	function generateRoundHundred(history) {
		let attempts = 0;
		while (attempts++ < 20) {
			const base = [100, 200, 300, 400, 500, 600, 700, 800, 900][Math.floor(Math.random() * 9)];
			const num = Math.floor(Math.random() * 50) + 1;
			const isAdd = Math.random() > 0.5;
			const answer = isAdd ? base + num : base - num;

			const question = {
				expression: `${base} ${isAdd ? '+' : '-'} ${num}`,
				answer: answer
			};

			if (validateQuestion(question, history)) {
				history.add(`${question.expression}=${question.answer}`);
				return question;
			}
		}
		return {
			expression: "300 - 45",
			answer: 255
		};
	}

	// 3. 三位数加法
	function generateThreeDigitAdd(history) {
		let attempts = 0;
		while (attempts++ < 20) {
			const num1 = Math.floor(Math.random() * 900) + 100;
			const num2 = Math.floor(Math.random() * 900) + 100;
			const answer = num1 + num2;

			const question = {
				expression: `${num1} + ${num2}`,
				answer: answer
			};

			if (validateQuestion(question, history)) {
				history.add(`${question.expression}=${question.answer}`);
				return question;
			}
		}
		return {
			expression: "156 + 278",
			answer: 434
		};
	}

	// 4. 三位数减法（确保非负）
	function generateThreeDigitSub(history) {
		let attempts = 0;
		while (attempts++ < 20) {
			const num1 = Math.floor(Math.random() * 900) + 100;
			const num2 = Math.floor(Math.random() * num1) + 1;
			const answer = num1 - num2;

			const question = {
				expression: `${num1} - ${num2}`,
				answer: answer
			};

			if (validateQuestion(question, history)) {
				history.add(`${question.expression}=${question.answer}`);
				return question;
			}
		}
		return {
			expression: "325 - 178",
			answer: 147
		};
	}

	// 5. 三位数加减混合
	function generateThreeDigitAddSub(history) {
		return Math.random() > 0.5 ?
			generateThreeDigitAdd(history) :
			generateThreeDigitSub(history);
	}

	// 6. 多数相加（3-5个数）
	function generateMultiAdd(history) {
		let attempts = 0;
		while (attempts++ < 20) {
			const count = Math.floor(Math.random() * 3) + 3;
			const numbers = [];
			let sum = 0;

			for (let i = 0; i < count; i++) {
				const num = Math.floor(Math.random() * 100) + 1;
				numbers.push(num);
				sum += num;
			}

			const question = {
				expression: numbers.join(' + '),
				answer: sum
			};

			if (validateQuestion(question, history)) {
				history.add(`${question.expression}=${question.answer}`);
				return question;
			}
		}
		return {
			expression: "12 + 34 + 56",
			answer: 102
		};
	}

	// 7. 两位数乘一位数
	function generateTwoDigitMulOneDigit(history) {
		let attempts = 0;
		while (attempts++ < 20) {
			const num1 = Math.floor(Math.random() * 90) + 10;
			const num2 = Math.floor(Math.random() * 9) + 1;
			const answer = num1 * num2;

			const question = {
				expression: `${num1} × ${num2}`,
				answer: answer
			};

			if (validateQuestion(question, history)) {
				history.add(`${question.expression}=${question.answer}`);
				return question;
			}
		}
		return {
			expression: "24 × 3",
			answer: 72
		};
	}

	// 8. 三位数乘一位数
	function generateThreeDigitMulOneDigit(history) {
		let attempts = 0;
		while (attempts++ < 20) {
			const num1 = Math.floor(Math.random() * 900) + 100;
			const num2 = Math.floor(Math.random() * 9) + 1;
			const answer = num1 * num2;

			const question = {
				expression: `${num1} × ${num2}`,
				answer: answer
			};

			if (validateQuestion(question, history)) {
				history.add(`${question.expression}=${question.answer}`);
				return question;
			}
		}
		return {
			expression: "123 × 4",
			answer: 492
		};
	}

	// 9. 两位数乘11（速算）
	function generateTwoDigitMul11(history) {
		let attempts = 0;
		while (attempts++ < 20) {
			const num = Math.floor(Math.random() * 90) + 10;
			const answer = num * 11;

			const question = {
				expression: `${num} × 11`,
				answer: answer
			};

			if (validateQuestion(question, history)) {
				history.add(`${question.expression}=${question.answer}`);
				return question;
			}
		}
		return {
			expression: "35 × 11",
			answer: 385
		};
	}

	// 10. 两位数乘15（速算）
	function generateTwoDigitMul15(history) {
		let attempts = 0;
		while (attempts++ < 20) {
			const num = Math.floor(Math.random() * 90) + 10;
			const answer = num * 15;

			const question = {
				expression: `${num} × 15`,
				answer: answer
			};

			if (validateQuestion(question, history)) {
				history.add(`${question.expression}=${question.answer}`);
				return question;
			}
		}
		return {
			expression: "20 × 15",
			answer: 300
		};
	}

	// 11. 两位数乘两位数
	function generateTwoDigitMulTwoDigit(history) {
		let attempts = 0;
		while (attempts++ < 20) {
			const num1 = Math.floor(Math.random() * 90) + 10;
			const num2 = Math.floor(Math.random() * 90) + 10;
			const answer = num1 * num2;

			const question = {
				expression: `${num1} × ${num2}`,
				answer: answer
			};

			if (validateQuestion(question, history)) {
				history.add(`${question.expression}=${question.answer}`);
				return question;
			}
		}
		return {
			expression: "12 × 15",
			answer: 180
		};
	}

	// 12. 常见平方数
	function generateCommonSquares(history) {
		const squares = [11,12,13,14,15,16,17,18,19,20,25,30,35,40,45,50];
		let attempts = 0;

		while (attempts++ < 20) {
			const num = squares[Math.floor(Math.random() * squares.length)];
			const answer = num * num;

			const question = {
				expression: `${num}²`,
				answer: answer
			};

			if (validateQuestion(question, history)) {
				history.add(`${question.expression}=${question.answer}`);
				return question;
			}
		}
		return {
			expression: "12²",
			answer: 144
		};
	}

	// 13. 三位数除以一位数（确保整除）
	function generateThreeDigitDivOneDigit(history) {
		let attempts = 0;
		while (attempts++ < 20) {
			const divisor = Math.floor(Math.random() * 9) + 1;
			const quotient = Math.floor(Math.random() * 100) + 10;
			const dividend = divisor * quotient;

			if (dividend < 100 || dividend > 999) continue;

			const question = {
				expression: `${dividend} ÷ ${divisor}`,
				answer: quotient
			};

			if (validateQuestion(question, history)) {
				history.add(`${question.expression}=${question.answer}`);
				return question;
			}
		}
		return {
			expression: "144 ÷ 6",
			answer: 24
		};
	}

	// 14. 三位数除以两位数（确保整除）
	function generateThreeDigitDivTwoDigit(history) {
		let attempts = 0;
		while (attempts++ < 20) {
			const divisor = Math.floor(Math.random() * 90) + 10;
			const quotient = Math.floor(Math.random() * 10) + 1;
			const dividend = divisor * quotient;

			if (dividend < 100 || dividend > 999) continue;

			const question = {
				expression: `${dividend} ÷ ${divisor}`,
				answer: quotient
			};

			if (validateQuestion(question, history)) {
				history.add(`${question.expression}=${question.answer}`);
				return question;
			}
		}
		return {
			expression: "225 ÷ 15",
			answer: 15
		};
	}

	// 15. 乘法估算（到百位）
	function generateEstimation(history) {
		let attempts = 0;
		while (attempts++ < 20) {
			const base = Math.floor(Math.random() * 9 + 1) * 100;
			const variation = Math.floor(Math.random() * 20) - 10;
			const num = base + variation;
			const answer = Math.round(num / 100) * 100;

			const question = {
				expression: `${num} ≈ ? (到百位)`,
				answer: answer
			};

			if (validateQuestion(question, history)) {
				history.add(`${question.expression}=${question.answer}`);
				return question;
			}
		}
		return {
			expression: "387 ≈ ?",
			answer: 400
		};
	}

	// 16. 五位数除以三位数（确保整除）
	function generateFiveDigitDivThreeDigit(history) {
		let attempts = 0;
		while (attempts++ < 20) {
			const divisor = Math.floor(Math.random() * 900) + 100;
			const quotient = Math.floor(Math.random() * 100) + 1;
			const dividend = divisor * quotient;

			if (dividend < 10000 || dividend > 99999) continue;

			const question = {
				expression: `${dividend} ÷ ${divisor}`,
				answer: quotient
			};

			if (validateQuestion(question, history)) {
				history.add(`${question.expression}=${question.answer}`);
				return question;
			}
		}
		return {
			expression: "10000 ÷ 100",
			answer: 100
		};
	}


	// 开始计时
	const startTimer = () => {
		timer = setInterval(() => {
			currentTime.value++;
		}, 1000);
	};

	// 停止计时
	const stopTimer = () => {
		clearInterval(timer);
	};

	// 输入数字
	const inputNumber = (num) => {
		if (num === '.' && userAnswer.value.includes('.')) return;
		if (userAnswer.value.length >= 8) return; // 限制输入长度
		userAnswer.value += num;
	};

	// 退格
	const backspace = () => {
		userAnswer.value = userAnswer.value.slice(0, -1);
	};

	// 清空答案
	const clearAnswer = () => {
		userAnswer.value = '';
	};

	// 检查答案
	const checkAnswer = () => {
		if (userAnswer.value === '') return;

		const isCorrect = parseFloat(userAnswer.value) === currentQuestionData.value.answer;
		if (isCorrect) correctCount.value++;

		// 显示快速反馈
		uni.showToast({
			title: isCorrect ? '回答正确!' : '回答错误',
			icon: isCorrect ? 'success' : 'none',
			duration: 500
		});

		// 快速进入下一题
		setTimeout(() => {
			if (currentQuestion.value < totalQuestions.value) {
				nextQuestion();
			} else {
				finishPractice();
			}
		}, 500);
	};

	// 下一题
	const nextQuestion = () => {
		currentQuestion.value++;
		currentQuestionData.value = questions.value[currentQuestion.value - 1];
		userAnswer.value = '';
	};

	// 完成练习
	const finishPractice = () => {
		stopTimer();
		uni.showModal({
			title: '练习完成',
			content: `正确率: ${Math.round(correctCount.value / totalQuestions.value * 100)}%\n用时: ${formatTime(currentTime.value)}`,
			confirmText: '再来一组',
			cancelText: '返回',
			success: (res) => {
				if (res.confirm) {
					restartPractice();
				} else {
					uni.navigateBack();
				}
			}
		});
	};

	// 重新开始
	const restartPractice = () => {
		stopTimer();
		currentTime.value = 0;
		currentQuestion.value = 1;
		correctCount.value = 0;
		userAnswer.value = '';
		generateQuestions();
		startTimer();
	};

	// 初始化
	onMounted(() => {
		uni.setNavigationBarTitle({
			title: props.practiceType
		});
		generateQuestions();
		startTimer();
	});

	// 清理
	onUnmounted(() => {
		stopTimer();
	});
</script>

<style lang="scss">
	/* 样式保持与之前相同 */
	.practice-container {
		height: 100vh;
		display: flex;
		flex-direction: column;
		background: linear-gradient(to bottom, #f7fbfe, #e6f2ff);
		overflow: hidden;
	}

	.status-bar {
		padding: 20rpx 30rpx;
		display: flex;
		justify-content: space-between;
		background-color: white;
		box-shadow: 0 2rpx 10rpx rgba(74, 140, 255, 0.1);

		.time,
		.progress,
		.practice-type {
			font-size: 28rpx;
			color: #4a8cff;
			font-weight: 500;
		}

		.practice-type {
			position: absolute;
			left: 50%;
			transform: translateX(-50%);
		}
	}

	.content-area {
		flex: 1;
		display: flex;
		flex-direction: column;
		padding: 30rpx;
		overflow: hidden;
	}

	.question-section {
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: center;
	}

	.question-container {
		background-color: white;
		border-radius: 20rpx;
		padding: 40rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 4rpx 12rpx rgba(74, 140, 255, 0.1);
		text-align: center;

		.question {
			font-size: 72rpx;
			font-weight: bold;
			color: #2a5caa;
			margin-bottom: 30rpx;
		}

		.answer-display {
			min-height: 80rpx;

			.answer {
				font-size: 60rpx;
				color: #4a8cff;
			}
		}
	}

	.standards {
		text-align: center;
		font-size: 26rpx;
		color: #7a9ccc;
		margin-bottom: 20rpx;
	}

	.action-buttons {
		height: 110rpx;
		display: flex;
		justify-content: space-between;
		margin: 20rpx 0;
		gap: 20rpx;

		.btn {
			display: flex;
			align-items: center;
			justify-content: center;
			height: 100%;
			border-radius: 50rpx;
			font-size: 32rpx;
			font-weight: 500;

			&.restart {
				flex: 0 0 40%;
				background: linear-gradient(135deg, #FF6B6B, #FF8E8E);
				color: white;
				box-shadow: 0 4rpx 12rpx rgba(255, 107, 107, 0.3);

				uni-icons {
					margin-right: 10rpx;
				}
			}

			&.clear {
				background-color: #ffecec;
				color: #ff6b6b;
				flex: 1;
			}

			&.backspace {
				background-color: #fff4e6;
				color: #ffa502;
				flex: 1;
			}

			&:active {
				opacity: 0.8;
				transform: scale(0.98);
			}
		}
	}

	.number-pad {
		padding: 30rpx;
		display: grid;
		grid-template-columns: repeat(3, 1fr);
		gap: 25rpx;
		background-color: white;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
		min-height: 380rpx;

		.num-btn {
			height: 110rpx;
			line-height: 110rpx;
			text-align: center;
			background-color: #f8faff;
			border-radius: 16rpx;
			font-size: 38rpx;
			color: #4a8cff;
			transition: all 0.1s;

			&.confirm {
				background: linear-gradient(to right, #4a8cff, #6ab5ff);
				color: white;
				font-weight: bold;
			}

			&:active {
				background-color: #e6f2ff;
				transform: scale(0.96);

				&.confirm {
					background: linear-gradient(to right, #3a7cdf, #5aa5ef);
				}
			}
		}
	}
</style>